var fs = require("fs");
var filePath = "test.txt";
var readline = require("readline");


function cl(d) {
    console.log(d)
}

function listenerv1() {
    "监听程序修改"
    fs.watch(filePath, function (event, filename) {
        cl("event is:" + event);
        if (filename) {
            cl('filename: ' + filename);
        } else {
            cl('filename not provided')
        }
    });
    cl(filePath + "listener...");
}

var filename = 'test.txt';

function reads() {
    "按行读取文件"
    var rs = readline.createInterface({
        input: fs.createReadStream(filename, {
            enconding: 'utf8'
        }),
        output: null
    }).on("line", function (line, err) {
        if (line) cl(line.toString());
        if (err) cl(err.message)
    }).on("close", function () {
        cl("read over")
    });
}

var Client=function () {
    this.debug =true
};
var client =new Client();
function listenFileUP() {
    "检查文件是否被修改"
    fs.open(filePath,'a+',function(error,fd){
        fs.watchFile(filePath,{
            persistent: true,
            interval: 1000 //等待1秒后回馈监听
        },function(ntime, otime){
            if(client.debug) cl(ntime);
            if(ntime.mtime>otime.mtime){  //otime原来时间，ntime时间
                buf = new Buffer(ntime.size - otime.size);//缓冲创建新-旧的长度
                fs.read(fd,buf,0,(ntime.size - otime.size),ntime.size,function(err, bytesRead, buffer){
                    cl(buf.toString());
                    cl("文件被修改了")
                });
            }else{
                cl('文件读取错误');
            }
        });
    });
}
